package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowData;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowProperties;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowResponse;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DeviceDataDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.dto.FamilyDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IWechatService;
import com.zzyl.nursing.util.DateTimeZoneConverter;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import com.zzyl.nursing.vo.FamilyMemberElderVo;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 *
 * @author syl
 * @date 2025-05-30
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember)?1:0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember)?1:0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private IWechatService wechatService;

    @Autowired
    private TokenService tokenService;  //这是zzyl-framework模块中的

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        String code = dto.getCode();
        String phoneCode = dto.getPhoneCode();

        // 调用微信接口返回openid
        String openid = wechatService.getOpenid(code);

        // 根据openid查询客户信息
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(queryWrapper);

        String phone = wechatService.getPhone(phoneCode); //这里要注意获取手机号用的是phoneCode
        if(familyMember==null){
            familyMember = new FamilyMember();
            familyMember.setPhone(phone);
            //从DEFAULT_NICKNAME_PREFIX随机挑选一个 + 手机号的后四位 0-8
            familyMember.setName(DEFAULT_NICKNAME_PREFIX.get(new Random().nextInt(DEFAULT_NICKNAME_PREFIX.size()))+phone.substring(7));
            familyMember.setOpenId(openid);
            familyMemberMapper.insert(familyMember);
        }else{
            // 这个用户是否修改过手机号
            if (!StrUtil.equals(familyMember.getPhone(),phone)) {
                familyMember.setPhone(phone);
            }
            familyMemberMapper.updateById(familyMember);

        }
        // 根据用户ID和昵称生成Jwt的token
        Map<String, Object> map = new HashMap();
        map.put("id", familyMember.getId());
        map.put("nickName", familyMember.getName());
        String token = tokenService.createToken(map); //这里注意把tokenService.createToken改成public

        LoginVo  loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Override
    public void bindingFamily(FamilyDto familyDto) {
        Long userId = UserThreadLocal.getUserId();
        Long elderidByName = elderMapper.getElderidByName(familyDto.getName());
        FamilyMemberElder bind = new FamilyMemberElder();
        bind.setMemberId(userId);
        bind.setElderId(elderidByName);
        bind.setRemark(familyDto.getRemark());
        long timestamp = System.currentTimeMillis();
        Date now = new Date(timestamp);
        bind.setCreateTime(now);
        familyMemberElderMapper.insertFamilyMemberElder(bind);
    }

    @Override
    public List<ElderFamilyDto> getMyFamily() {
        Long userId = UserThreadLocal.getUserId();
        List<FamilyMemberElder> myFamilys = familyMemberElderMapper.selectMyFamily(userId);
        List<ElderFamilyDto> myFamily = new ArrayList<>();
        for (FamilyMemberElder MyFamilyData : myFamilys) {
            Elder elder = elderMapper.selectElderById(MyFamilyData.getElderId());
            ElderFamilyDto dto = new ElderFamilyDto();
            BeanUtils.copyProperties(elder,dto);
            dto.setKinship(MyFamilyData.getRemark());
            myFamily.add(dto);
        }
        return myFamily;
    }

    @Override
    public List<FamilyMemberElderVo> getFamilyList(Long userId,Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<FamilyMemberElder> familyMemberElders = familyMemberElderMapper.selectFamilyList(userId);
        List<FamilyMemberElderVo> elderFamilyVos = new ArrayList<>();
        for (FamilyMemberElder familyMemberElder : familyMemberElders) {
            FamilyMemberElderVo elderFamilyVo = new FamilyMemberElderVo();
            elderFamilyVo.setMid(familyMemberElder.getMemberId());
            elderFamilyVo.setMremark(familyMemberElder.getRemark());
            elderFamilyVo.setElderId(familyMemberElder.getElderId());
            Elder elder = elderMapper.selectElderById(familyMemberElder.getElderId());
            elderFamilyVo.setName(elder.getName());
            elderFamilyVo.setImage(elder.getImage());
            elderFamilyVo.setBedNumber(elder.getBedNumber());
            String bedNumber = elder.getBedNumber();
            String[] split = bedNumber.split("-");
            String code = split[0];
            Room room = roomMapper.selectRoomByCode(code);
            if (room != null){
                elderFamilyVo.setTypeName(room.getTypeName());
            }
            Device device = deviceMapper.selectDeviceByName(elder.getName());//TODO 获取设备信息
            if (device != null){
                elderFamilyVo.setIotId(device.getIotId());
                elderFamilyVo.setDeviceName(device.getDeviceName());
                elderFamilyVo.setPrductKey(device.getProductKey());
            }
            elderFamilyVos.add(elderFamilyVo);
        }
        return elderFamilyVos;
    }

    @Autowired
    private IoTDAClient ioTDAClient;
    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        List<DeviceDataVo> list = new ArrayList<>();
        // IOT查询数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("IOT设备查询失败");
        }

        List<DeviceShadowData> shadowList = response.getShadow();
        if (CollUtil.isNotEmpty(shadowList)) {


            DeviceShadowData deviceShadowData = shadowList.get(0);
            DeviceShadowProperties reported = deviceShadowData.getReported();
            String eventTimeStr = reported.getEventTime();//20250601 T 08 24 34 Z
            LocalDateTime eventTimeUTC = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeUTC);

            Object properties = reported.getProperties();
            JSONObject jsonObject = JSONUtil.parseObj(properties);
            jsonObject.forEach((key, value) -> {
                DeviceDataVo deviceDataVo = new DeviceDataVo();
                deviceDataVo.setFunctionId(key);
                deviceDataVo.setEventTime(eventTime);
                deviceDataVo.setValue(value);
                list.add(deviceDataVo);
            });


        }
        return list;
    }

    @Override
    public List<DeviceDataVo> queryDeviceDataListByDay(DeviceDataDto dto) {
        LocalDateTime startTime = LocalDateTimeUtil.of(dto.getStartTime());
        LocalDateTime endTime = LocalDateTimeUtil.of(dto.getEndTime());
        List<DeviceDataVo> voList = familyMemberMapper.getHour(dto.getIotId(), dto.getFunctionId(), startTime, endTime);
        List<DeviceDataVo> list = new ArrayList<>();
        for (int i = 0; i < 25; i++) {
            final int finalHour = i;
            DeviceDataVo deviceDataVo = voList.stream().filter(vo -> vo != null && vo.getHour() != null && vo.getHour() == finalHour).findFirst().orElse(null);
            if (deviceDataVo != null) {
                list.add(deviceDataVo);
            } else {
                DeviceDataVo deviceDataVo1 = new DeviceDataVo();
                deviceDataVo1.setDateTime(String.format("%02d:00", finalHour));
                deviceDataVo1.setDataValue(50.0);
                list.add(deviceDataVo1);
            }
        }
        return list;
    }

    @Override
    public List<DeviceDataVo> queryDeviceDataListByWeek(DeviceDataDto dto) {
        // 将时间戳转换为LocalDateTime
        LocalDateTime startTime = LocalDateTimeUtil.of(dto.getStartTime());
        LocalDateTime endTime = LocalDateTimeUtil.of(dto.getEndTime());

        // 查询一周内的设备数据（按天分组）
        List<DeviceDataVo> voList = familyMemberMapper.getDay(dto.getIotId(), dto.getFunctionId(), startTime, endTime);

        List<DeviceDataVo> list = new ArrayList<>();
        // 一周有7天，循环处理每天的数据
        for (int i = 0; i < 7; i++) {
            final int finalDay = i;
            // 查找对应天的数据
            DeviceDataVo deviceDataVo = voList.stream()
                    .filter(vo -> vo != null && vo.getDay() != null && vo.getDay() == finalDay)
                    .findFirst()
                    .orElse(null);

            if (deviceDataVo != null) {
                list.add(deviceDataVo);
            } else {
                // 若当天无数据，构造默认数据
                DeviceDataVo deviceDataVo1 = new DeviceDataVo();
                // 格式化显示为周几（0代表周日，1代表周一...6代表周六，可根据业务调整）
                deviceDataVo1.setDateTime("周" + (finalDay == 0 ? "日" : finalDay));
                deviceDataVo1.setDataValue(50.0);
                list.add(deviceDataVo1);
            }
        }
        return list;
    }


    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

}
